#unique_found.pl
#author: Jeremy Cothran (jeremy.cothran@gmail.com)
#date: March 28, 2008

use strict;

@ARGV = glob 'found/found*';

my %summary_hash_seq = ();
my $r_summary_hash_seq = \%summary_hash_seq;

while (my $found_file = shift @ARGV) {
#print $found_file."\n";

my $unique_found_file = 'unique_'.substr($found_file,6);
#print $unique_found_file."\n";

my %hash_seq = ();
my $r_hash_seq = \%hash_seq;

open (FILE_IN,"$found_file");

my $full_line = '';

my $line;
while ($line = <FILE_IN>) {

if ($line =~ /^#/ || $line =~ /^\s/ || $line=~ /^>/) {
  print $full_line."\n";
  $hash_seq{seq}{$full_line}{count}++;
  $summary_hash_seq{seq}{$full_line}{count}++;

  $full_line = '';
  next;
}

chomp($line);
$full_line .= $line;
}
close(FILE_IN);


#print this file - sorted hash of sequences
open (FILE_OUT,">found/$unique_found_file");

my @seq = reverse sort { $hash_seq{seq}{$a}{count} <=> $hash_seq{seq}{$b}{count} } keys %{$r_hash_seq->{seq}};

foreach my $seq (@seq) {

	my $count_seq = $hash_seq{seq}{$seq}{count};

	print FILE_OUT "$count_seq\t$seq\n";
}
close(FILE_OUT);

} #while @ARGV

##############################################################

#print summary file - sorted hash of sequences
open (FILE_OUT,">found/summary_unique_found.txt");

my @seq = reverse sort { $summary_hash_seq{seq}{$a}{count} <=> $summary_hash_seq{seq}{$b}{count} } keys %{$r_summary_hash_seq->{seq}};

foreach my $seq (@seq) {

	my $count_seq = $summary_hash_seq{seq}{$seq}{count};

	print FILE_OUT "$count_seq\t$seq\n";
}
close(FILE_OUT);

exit 0;

